package com.lnb.gateway.filter;

import cn.hutool.core.util.IdUtil;
import com.lnb.common.constant.BaseConstant;
import com.lnb.gateway.constant.Constant;
import com.lnb.gateway.util.IPUtils;
import lombok.extern.log4j.Log4j2;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * <p>
 *  请求日志记录拦截器
 * </p>
 *
 * @author liaoningbo
网关过滤器，接口执行完成之后再执行 * @since 2024-01-08
 */
@Component
@Log4j2
public class LogFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //设置唯一请求id
        String traceId = IdUtil.fastUUID();
        MDC.put(BaseConstant.TRACE_ID, traceId);
        long startTime = System.currentTimeMillis();
        log.info("日志拦截开始, startTime:{}", startTime);
        ServerHttpRequest request = exchange.getRequest();
        exchange.getRequest().mutate().headers(httpHeaders -> httpHeaders.add(BaseConstant.TRACE_ID, traceId));
        //打印请求参数
        log.info("url:{}, ip:{}, method:{}", request.getPath(), IPUtils.getIpAddress(request), request.getMethod());
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            long endTime = System.currentTimeMillis();
            log.info("请求完成，endTime:{}, 耗时:{}ms", endTime, System.currentTimeMillis() -  startTime);
            MDC.clear();
        }));
    }

    @Override
    public int getOrder() {
        return Constant.LOG_FILTER_ORDER;
    }
}
